package com.scalar.chiptrack.sales.jobs;

import com.scalar.ScalarException;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.sales.reports.dao.DataDumpDao;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.Logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * User: Sujan
 * Date: Jan 8, 2008
 * Time: 1:25:02 PM
 */
public class SalesInvoicingGenerateFileJob extends JobHandler
{
    private static Logger m_parserLogger    = null;
    private String m_dataOutputDir          = null;
    private String m_dataOutputFileName     = null;

    public SalesInvoicingGenerateFileJob() throws ScalarException
    {
        try
        {
            m_dataOutputDir = DataDumpDao.getFileLocation( "SO" );
            m_dataOutputFileName = DataDumpDao.getFileName( "SO" );
            AdaptorUtils.makeAllAdaptorDirs(m_dataOutputDir);
            m_parserLogger = AdaptorUtils.getDataParserLogger(m_dataOutputDir, "SlaesInvoice");
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading Sales Invoicing Job output directory details from database, Exception: " + se);
            throw se;
        }
    }
    // To be implemented by sub classes
    public void execute() throws Exception
    {
        printVersionInfo();
        FileWriter fw = null;
        try
        {
            String salesInvoicingCSVString = DataDumpDao.getSalesInvoicingInfoCSVString();

            String fileName = m_dataOutputFileName + "_"+ DateUtil.getTimeStamp() + ".CSV";

            if ( m_dataOutputDir != null && fileName != null )
            {
                boolean exists = ( new File( m_dataOutputDir ) ).exists();
                if ( !exists )
                {
                    File file = new File( m_dataOutputDir );
                    file.mkdirs();
                }
                File file1 = new File( m_dataOutputDir + "/" + fileName );
                fw = new FileWriter( file1 );
                fw.write( salesInvoicingCSVString );
                log( "File: " + m_dataOutputDir + "/" + fileName + " saved Successfully");
                System.out.println ( "File: " + m_dataOutputDir + "/" + fileName + " saved Successfully" );
            }
            else
            {
                log ( "Error: Could not find the File path and File name" );
                throw new Exception( "Could not find the File path and File name" );
            }
       	}
        catch ( Exception e )
        {
            log ( "Could not save the file to disk", e );
            System.out.println( "Could not save the file to disk" );
            e.printStackTrace();
            throw e;
        }
        finally
        {
            if ( fw != null )
            {
                try
                {
                    fw.flush();
                } catch ( IOException ignore ) {}
                try
                {
                    fw.close();
                }catch ( IOException ignor ) {}
            }
        }
    }
    private void log(String message)
    {
        if (message == null) return;

        if (m_parserLogger != null)
        {
            synchronized (m_parserLogger)
            {
                m_parserLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
    private void log(String message, Throwable e )
    {
        if (m_parserLogger != null)
        {
            synchronized (m_parserLogger)
            {
                m_parserLogger.logError(message + LINE_SEPARATOR, e );
            }
        }
        else
        {
            System.out.println(message);
            e.printStackTrace();
        }
    }

    private void printVersionInfo()
    {
        String info = "\n\n+----------- Running Sales Invoicing Generate File Job on " + new java.util.Date(System.currentTimeMillis()) + " -------------+\n" +
               "\n+---------------------------------------------------------------+\n" +
               "+                                                                \n" +
               "+            Sales Invoicing Generate File Job - Beta            \n" +
               "+                                                                \n" +
               "+    Copy Right (C) 2008 - ScalarSoft Inc., All rights reserved.  \n" +
               "+                                                                \n" +
               "+---------------------------------------------------------------+\n";
        System.out.println(info);
        log(info);
    } //end of printVersionInfo
}
